package com.acmen.easyapi.validation.validator;

import com.acmen.easyapi.util.StringUtil;
import com.acmen.easyapi.validation.DataTypeValidator;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 数字校验器
 *
 * @author acmen
 * @date 2022-04-06
 */
@Component
public class NumberValidator implements DataTypeValidator {
    private final static String PATTERN = "^num\\((([1-9][0-9]*)+(\\.[0-9]{1,3})?),(([1-9][0-9]*)+(\\.[0-9]{1,3})?)\\)";

    public boolean matches(String exp) {
        boolean isMatch = Pattern.matches(PATTERN, exp);
        return isMatch;
    }

    @Override
    public void validate(String exp, Object data, List<String> messages) {
        Double value = Double.parseDouble(data.toString());
        exp = exp.trim();
        exp = exp.substring("num(".length());
        exp = exp.substring(0, exp.length() - 1);
        String[] nums = exp.split(",");
        Double min = Double.parseDouble(nums[0]);
        if (value < min) {
            messages.add("不能小于" + nums[0] + "！");
        }
        Double max = Double.parseDouble(nums[1]);
        if (value > max) {
            messages.add("不能大于" + nums[1] + "！");
        }
    }

    /**
     * 校验说明
     *
     * @return
     */
    @Override
    public String getNote(String exp) {
        if(StringUtil.isNotEmpty(exp)){
            exp = exp.trim();
            exp = exp.substring("num(".length());
            exp = exp.substring(0, exp.length() - 1);
            String[] nums = exp.split(",");
            String min = nums[0];
            String max = nums[1];
            return "数据必需是大于等于"+min+"且小于等于"+max+"的数字；";
        }
        return "num(min,max)：数据必需是大于min且小于max的数字；";
    }
}
